/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2022-05-16
 * Time: 22:21
 */

class Money implements Cloneable{
    public double money = 19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class People implements Cloneable{  //Cloneable 标志 People 这个类可以被克隆
    public int age = 10;
    public Money m = new Money();

    //重写 clone 方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        People tmp = (People) super.clone();
        tmp.m = (Money) this.m.clone();
        return tmp;  //深拷贝的写法

        //return super.clone();  //浅拷贝的写法
    }

    @Override
    public String toString() {
        return "People{" +
                "age=" + age +
                '}';
    }

}

public class Test {

    public static void main(String[] args) throws CloneNotSupportedException{
        People people1 = new People();
        People people2 = (People) people1.clone();
        System.out.println(people1);
        System.out.println(people2);
        System.out.println(people1.m.money);
        System.out.println(people2.m.money);

        System.out.println("================");
        people2.age = 29;  //通过people2改变age 的值，不会影响 people1 中age的值
                            //这就是浅拷贝

        people1.m.money = 39.9; //通过people2改变money 的值，不会影响 people1 中money的值就是深拷贝
                                //反之是浅拷贝
        System.out.println(people1);
        System.out.println(people2);
        System.out.println(people1.m.money);
        System.out.println(people2.m.money);
    }
}
